import Menu from 'ant-design-vue/es/menu'
import { computed, h, toRaw } from 'vue'
import aIcon from '@/components/a-icon/a-icon'
import { useStore } from 'vuex';
import { RouterLink } from 'vue-router';

const {Item, SubMenu} = Menu
const menuList = []

/**
 * 生成icon
 *
 * @param {*} iconName
 */
function renderIcon(menu){
  if(menu.meta && menu.meta.icon){
    return h(aIcon, {name: menu.meta.icon})
  }else{
    return null
  }
}

/**
 * 生成 a-sub-menu
 *
 * @param {*} menu 当前操作的路由
 */
function renderSubMenu(menu){
  // 添加子menu
  const childMenuArr = []
  menu.children.forEach(childItem => {
    childMenuArr.push(renderItem(childItem))
  })
  return h(
    SubMenu,
    {key: menu.fullPath,},
    {
      title: () => menu.name,
      icon: () => renderIcon(menu),
      default: () => childMenuArr
    }
  )
}

/**
 * 生成 a-menu-item
 *
 * @param {*} menu 当前操作的路由
 */
function renderMenuItem(menu){
  const path = menu.fullPath
  const query = menu.meta ? menu.meta.query : {}
  let config = {
    to:{
      path,
      query,
    },
    style: {overflow:'hidden',whiteSpace:'normal',textOverflow:'clip',}
  } 
  return h(
    Item,
    {
      key: menu.fullPath,
    },
    {
      default: () => h(RouterLink, config, () => [
        renderIcon(menu),
        menu.name
      ])
    }
  )
}

/**
 * 判断以什么方式进行 render
 *
 * @param {*} menu 当前操作的路由
 */
function renderItem(menu){
  const mate = menu.mate
  if(!mate || !mate.invisible){
    // 判断children是否存在，存在则渲染 subMenu, 
    //不存在或全部为 invisible=true,则渲染itemMenu
    let renderChild = false
    if(menu.children != undefined){
      for(let item in menu.children){
        let itemMate = item.mate
        if(!itemMate || !itemMate.invisible){
          renderChild = true
        }
      }
    }
    return renderChild ? renderSubMenu(menu) : renderMenuItem(menu)
  }
}

/**
 *
 * 
 * @param {*} routes 路由参数
 * @returns 返回一个 h() 函数对象的数组
 */
function renderMenu(routes){
  menuList.splice(0) // 渲染时清空数据，防止重复渲染
  // console.log(routes)
  routes.forEach((muenItem) => {
    menuList.push(renderItem(muenItem))
  });
  return menuList
}

export default {
  setup() {
    const store = useStore()
    const menuData = computed(() => store.getters['menu/menuData'])
    return {
      menuData: toRaw(menuData.value),
    }
  },
  render(){
    return renderMenu(this.menuData)
  }
}